const { globalData, cloud } = getApp();
// var FunEngine = require('./FunEngine.js');
var FunEngine = require('./FunEngine_dome.js');

import * as THREE from './three.js';
import SourceData from '../source_data.js';

var winWidth;
var winHeight;
var CurrentIndex = 0;

var circlePosArray = [55 - 96, 55, 151, 247, 247 + 96];

var STATE = {
  NONE: -1,
  TOUCH_ROTATE: 0,
  TOUCH_ZOOM_PAN: 1,
  TOUCH_PAN: 2
};

var _state = STATE.NONE;
var _movePrev = new THREE.Vector2();
var _moveCurr = new THREE.Vector2();
var _touchZoomDistanceStart = 1;
var _touchZoomDistanceEnd = 1;
var _panStart = new THREE.Vector2();
var _panEnd = new THREE.Vector2();

var showSkyBoxDataId = 0;
var showSkyBoxPosId = 0; // 0:tag0 1:tag1
// var benifitUrl = "https://market.m.taobao.com/app/cem-fe/benefit-exchange/benefit-exchange/index.html?source=InterestsDetail&activityId=2824664";
var benifitUrl =    "https://market.m.taobao.com/app/cem-fe/benefit-exchange/benefit-exchange/index.html?source=InterestsDetail&activityId=3007167";

var test = false;

function getMouseOnScreen(pageX, pageY) {
  var vector = new THREE.Vector2();

  vector.set(
    (pageX) / winWidth,
    (pageY) / winHeight
  );

  return vector;
}

function getMouseOnCircle(pageX, pageY) {
  var vector = new THREE.Vector2();
  vector.set(
    ((pageX - winWidth * 0.5) / (winWidth * 0.5)),
    ((winHeight + 2 * (0 - pageY)) / winWidth)
  );

  return vector;
}

Page({
  data: {
    goodInfoShowList: SourceData.goodsInfoListData,

    showGuide: false,
    showGoodInfos: false,
    showCommonGuide: true,
    showJoinParty: false,

    guideShowType: 0, // 场景小人颜色不同
    joinShowType: 0, // 0 join  1 get
    inited: false,

    touchedTag: null,
    sceneShowDirectGuide: false,
    touchMoveSx: -1,
    touchMoveSy: -1,

    debugStr: "debug",
    showDebugStr: false,
  },

  canvasStart: function (event) {
    // var clickTag = FunEngine.GetClickedTag(event);
    // console.log("canvasStart clickTag = " + clickTag)
    // if (clickTag.indexOf('entry') != -1) {
    //   this.clickEntry(clickTag);
    //   return;
    // }
    var clickTag = FunEngine.GetClickedTag(event);
    this.setData({
      touchedTag: clickTag
    })

    var touchlen = event.touches.length;
    console.log("canvasStart touchlen = " + touchlen)
    switch (touchlen) {
      case 1:
        _state = STATE.TOUCH_ROTATE;
        _moveCurr.copy(getMouseOnCircle(event.touches[0].x, event.touches[0].y));
        // if (FunEngine.PLATFORM != "TAOBAO")
        //   _moveCurr.copy(getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY));

        _movePrev.copy(_moveCurr);

        this.setData({
          touchMoveSx: _movePrev.x,
          touchMoveSy: _movePrev.y,
        })

        break;
      case 2:
        break;
      default:
        _state = STATE.TOUCH_PAN;
        var x = (event.touches[0].x + event.touches[1].x) / 2;
        var y = (event.touches[0].y + event.touches[1].y) / 2;
        // if (FunEngine.PLATFORM != "TAOBAO") {
        //   x = (event.touches[0].pageX + event.touches[1].pageX) / 2;
        //   y = (event.touches[0].pageY + event.touches[1].pageY) / 2;
        // }

        _panStart.copy(getMouseOnScreen(x, y));
        _panEnd.copy(_panStart);
        break;
    }
    return;


    //my.alert({content: tagName});
  },
  canvasMove: function (event) {
    var clickTag = FunEngine.GetClickedTag(event);
    this.setData({
      touchedTag: clickTag
    })

    switch (event.touches.length) {
      case 1:
        if (_state === STATE.TOUCH_ROTATE) {

          _movePrev.copy(_moveCurr);
          //my.alert({content: event.touches[0]});
          _moveCurr.copy(getMouseOnCircle(event.touches[0].x, event.touches[0].y));
          // if (FunEngine.PLATFORM != "TAOBAO") {
          //   _moveCurr.copy(getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY));
          // }
          //_moveCurr.copy(new THREE.Vector2(event.touches[0].x, event.touches[0].y));


          var xOffset = _moveCurr.x - _movePrev.x;
          var yOffset = _moveCurr.y - _movePrev.y;
          if (_state == STATE.TOUCH_ROTATE) {
            xOffset *= 1;
            yOffset *= 1;
          }
          //my.alert({content: xOffset});
          FunEngine.SetSceneRot(xOffset, yOffset);
          //my.alert({content: xOffset});

          var moveDx = Math.abs(_moveCurr.x - this.data.touchMoveSx);
          var moveDy = Math.abs(_moveCurr.y - this.data.touchMoveSy);

          console.log("touchMoveSx : " + this.data.touchMoveSx)
          console.log("touchMoveSy : " + this.data.touchMoveSy)
          console.log("moveDx : " + moveDx)
          console.log("moveDy : " + moveDy)


          if ((moveDx > 0.05 || moveDy > 0.05) && this.data.sceneShowDirectGuide) {
            this.hideDirectGuide();
          }

        }
        //console.log(_moveCurr);
        break;
      default:
        _state = STATE.TOUCH_ZOOM_PAN;
        var dx = event.touches[0].x - event.touches[1].x;
        var dy = event.touches[0].y - event.touches[1].y;

        if (_touchZoomDistanceStart < 1.001 && _touchZoomDistanceStart > 0.999 && _touchZoomDistanceEnd < 1.001 && _touchZoomDistanceEnd > 0.999) {
          _touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt(dx * dx + dy * dy);
        } else {
          _touchZoomDistanceEnd = parseInt(Math.sqrt(dx * dx + dy * dy));
        }

        break;
    }
  },
  canvasEnd: function (event) {
    if (this.data.touchedTag.indexOf('entry') != -1) {
      var clickTag = this.data.touchedTag;
      this.clickEntry(clickTag);
      this.setData({
        touchedTag: null
      })
      return;
    }

    switch (event.touches.length) {
      case 0:
        _state = STATE.NONE;
        _touchZoomDistanceEnd = _touchZoomDistanceStart = 1;
        break;
      default:
        _state = STATE.NONE;
        _moveCurr.copy(getMouseOnCircle(event.touches[0].x, event.touches[0].y));
        _movePrev.copy(_moveCurr);
        _panStart.copy(_panEnd);
        break;
    }
  },

  onLoad() {
  },

  onShow() {
    // onLaunch() {
    if (this.data.inited && this.data.showJoinParty) {
      my.showLoading({
        content: '加载中...',
        delay: 0,
      });
      this.getMember();
    }

    if (this.data.inited)
      return;

    _state = STATE.NONE;
    _movePrev = new THREE.Vector2();
    _moveCurr = new THREE.Vector2();
    _touchZoomDistanceStart = 1;
    _touchZoomDistanceEnd = 1;
    _panStart = new THREE.Vector2();
    _panEnd = new THREE.Vector2();

    showSkyBoxDataId = 0;
    showSkyBoxPosId = 0; // 0:tag0 1:tag1


    // 页面显示
    var _self = this;
    var res = my.getSystemInfoSync();
    console.log(res);
    const { windowWidth, windowHeight } = res;
    this.setData({
      windowWidth,
      windowHeight,
      goodInfoShowList: SourceData.goodsInfoListData,
      inited: true
    }, () => {
      winWidth = windowWidth;
      winHeight = windowHeight;

      console.log([windowWidth, windowHeight]);

      // var skyUrl = 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/mmsVr/scene_2/sky_dome.png';

      // FunEngine.AddSkyDome(skyUrl,'tag0');

      // _self.setSkyBoxData('0', 0, false);
      // _self.setSkyBoxData('1', 1, true);

      try {
        FunEngine.InitEngine('canvasGL');
        var str = FunEngine.genDebugInfos();
        _self.setData({
          debugStr: str,
        })

        _self.setSkyBoxDataAndSwitch("0", 0);

      } catch (e) {
        console.log(e)
      }
    });
  },

  showDirectGuide() {
    // return;
    FunEngine.AddImage3D("direct_guide", -80, -13, -35,
      // rotateX, rotateY, 
      1.57, 1.73,
      0, 56, 40,
      "http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/mmsVr/direct_guide.png", 5);
    this.data.sceneShowDirectGuide = true;
  },

  hideDirectGuide() {
    // return;
    FunEngine.StartAlphaAnimation("direct_guide", 1.0, 0.0, 500);
    FunEngine.StartScaleAnimation("direct_guide", 1.0, 0.0, 1000);

    this.data.sceneShowDirectGuide = false;
  },

  /**
   * 加入会员dialog
   */
  changeJoinStatus() {
    let { showJoinParty } = this.data;
    this.setData({
      showJoinParty: !showJoinParty
    });
  },

  /**
   * mm引导dialog
   */
  changeGuideStatus() {
    let { showGuide } = this.data;
    this.setData({
      showGuide: !showGuide
    });
  },

  /**
   * 进入引导dialog
   */
  changeCommonGuideStatus() {
    let { showCommonGuide } = this.data;
    this.setData({
      showCommonGuide: !showCommonGuide
    });

    if (!this.data.sceneShowDirectGuide) {
      this.showDirectGuide();
    }
  },

  /**
   * 商品弹窗
   */
  changeGoodInfosStatus() {
    let { showGoodInfos } = this.data;
    this.setData({
      showGoodInfos: !showGoodInfos
    });
  },

  /**
   * 右上角点击
   */
  onMallClick() {
    // this.setData({
    //   showJoinParty: true
    // });

    my.showLoading({
      content: '加载中...',
      delay: 0,
    });

    this.getMember();
  },

  /**
   * 
   * @param {*} inId -----> scene id
   * @param {*} posId ----> tag0  tag1
   * @param {*} isEdit 
   */
  setSkyBoxData(inId, posId, isEdit) {
    for (var i = 0; i < SourceData.PicsData.length; i++) {
      var tempData = SourceData.PicsData[i];
      if (tempData.id == inId) {

        FunEngine.removeItemsByName("entry");
        // FunEngine.AddSkyBox(tempData.urls, posId == 0 ? "tag0" : "tag1", isEdit);

        if (!FunEngine.isHaveObject(posId == 0 ? "tag0" : "tag1"))
          FunEngine.AddSkyDome0(tempData.skyDomeImge, posId == 0 ? "tag0" : "tag1");

        // return ;

        // entries
        for (var j = 0; j < tempData.entries.length; j++) {
          var entry = tempData.entries[j];
          var _axisX = new THREE.Vector3(1, 0, 0);
          var _sprite = new THREE.Vector3(entry.position[0], entry.position[1], 0);

          var rotateY = _sprite.angleTo(_axisX) + Math.PI / 2;
          // var rotateY = 2.85;          
          var rotateX = Math.PI / 2;

          console.log("entry.imgUrl : " + entry.imgUrl);
          console.log("rotate : " + rotateX + " " + rotateY);

          // if (_sprite.y < 0)
          //   rotateX = 0 - rotateX;

          FunEngine.AddImage3D(entry.id, entry.position[0], entry.position[1], entry.position[2],
            // rotateX, rotateY, 
            entry.rotation[0], entry.rotation[1],
            0,
            entry.width, entry.height,
            entry.imgUrl, 5);

          if (entry.type == "goods") {
            FunEngine.StartPosition3DAnimation(entry.id,
              { x: entry.position[0], y: entry.position[1], z: entry.position[2] },
              { x: entry.position[0], y: entry.position[1], z: entry.position[2] + 2.5 },
              500,
              0,
              false,
              true);
          }

          if (entry.type == "hand") {
            FunEngine.StartPosition3DAnimation(entry.id,
              { x: entry.position[0], y: entry.position[1], z: entry.position[2] },
              { x: entry.position[0], y: entry.position[1], z: entry.position[2] + 2.5 },
              500,
              0,
              false,
              true);
          }

          // FunEngine.setNodeVisible(entry.id, false);

          // if (entry.type == "scene") {
          //   // var jsonData = SourceData.SpriteData;
          //   // var aniData = [];
          //   // for (var m = 1; m < 10; m++) {
          //   //   aniData.push('000' + m + '.jpg');
          //   // }
          //   // for (var m = 10; m < 48; m++) {
          //   //   aniData.push('00' + m + '.jpg');
          //   // }

          //   // FunEngine.AddSprite(entry.id, entry.position[0], entry.position[1], entry.position[2],
          //   //   rotateX, rotateY, 0, entry.width, entry.height,
          //   //   jsonData, 'https://morefun-active.oss-cn-beijing.aliyuncs.com/osm/images/seq/1334.png', aniData, 5);
          //   FunEngine.AddImage3D(entry.id, entry.position[0], entry.position[1], entry.position[2],
          //     rotateX, rotateY, 0, entry.width, entry.height,
          //     'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/PandoraVrMall/router.png', 5);
          // } else if (entry.type == "good") {
          //   FunEngine.AddImage3D(entry.id, entry.position[0], entry.position[1], entry.position[2],
          //     rotateX, rotateY, 0, entry.width, entry.height,
          //     'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/PandoraVrMall/location2.png', 5);
          // } else if (entry.type == "smallapp") {
          //   FunEngine.AddImage3D(entry.id, entry.position[0], entry.position[1], entry.position[2],
          //     rotateX, rotateY, 0, entry.width, entry.height,
          //     'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/PandoraVrMall/public_bg.jpg', 5);
          // }
        }
        break;
      }
    }
  },

  setSkyBoxDataAndSwitch(inId, posId) {
    this.countDown();

    this.setSkyBoxData(inId, posId, true);
    FunEngine.SwitchSkyBox(posId == 0 ? "tag0" : "tag1", posId != 0 ? "tag0" : "tag1", 500);
    showSkyBoxPosId = posId;
    showSkyBoxDataId = inId;
  },

  clickEntry(inTag) {
    for (var i = 0; i < SourceData.PicsData.length; i++) {
      console.log("i = " + i)
      var tempData = SourceData.PicsData[i];
      console.log("tempData = ")
      console.log(tempData)
      console.log("tempData.id = " + tempData.id + " showSkyBoxDataId = " + showSkyBoxDataId)

      if (tempData.id == showSkyBoxDataId) {
        for (var j = 0; j < tempData.entries.length; j++) {
          console.log("j = " + j)

          var tempEntry = tempData.entries[j];
          console.log("tempEntry = ")
          console.log(tempEntry)

          console.log("tempEntry.id = " + tempEntry.id + " inTag = " + inTag)

          if (tempEntry.id == inTag) {
            // 场景切换
            if (tempEntry.type == "scene") {
              var nextId = tempData.entries[j].nextSceneId;
              var posId = Math.abs(showSkyBoxPosId - 1);
              console.log("nextId = " + nextId + " posId = " + posId)
              this.setSkyBoxDataAndSwitch(nextId, posId);
            } else if (tempEntry.type == "goods") {
              // 商品列表
              // var goodId = tempEntry.goodId;
              // app.(nextId, posId);
              // this.onGoodMarkerClick(goodId);
              this.changeGoodInfosStatus();
            } else if (tempEntry.type == "dialog") {
              // mmr
              this.setData({
                guideShowType: tempEntry.dialogId, // 场景小人颜色不同
                showGuide: true,
              })
            }
            return;
          }
        }
      }
    }
  },

  // onKefuClick() {
  //   my.tb.openMessage({
  //     sellerNick: "商家测试账号",
  //     success: (res) => {
  //       console.log(res);
  //       console.log(res);
  //       my.alert({
  //         content: "启动客服成功" + res,
  //       });
  //     },
  //     fail: (res) => {
  //       console.log(res);
  //       my.alert({
  //         content: "启动客服失败" + res,
  //       });
  //     },
  //   })
  // },

  // onAddToCart(id, exts) {
  //   my.tb.addToCart({
  //     itemIds: id,
  //     exts: exts ? exts : '',
  //     success: (res) => {
  //       my.alert({ content: "success" + JSON.stringify(res) })
  //     },
  //     fail: (res) => {
  //       my.alert({ content: "fail" + JSON.stringify(res) })
  //       console.log(res)
  //     },
  //   })
  // }

  goChallenge() {
    // my.alert({ content: "goChallenge" });
    my.navigateToMiniProgram({
      appId: '3000000026212263',
      success: (res) => {
        console.log(JSON.stringify(res))
      },
      fail: (res) => {
        console.log(JSON.stringify(res))
      }
    });
  },

  goSign() {
    // my.alert({ content: "goSign" });
    my.navigateToMiniProgram({
      appId: '3000000026212933',
      success: (res) => {
        console.log(JSON.stringify(res))
      },
      fail: (res) => {
        console.log(JSON.stringify(res))
      }
    });
  },

  goMake() {
    // my.alert({ content: "goMake" });
    my.navigateToMiniProgram({
      appId: '3000000025288331',
      success: (res) => {
        console.log(JSON.stringify(res))
      },
      fail: (res) => {
        console.log(JSON.stringify(res))
      }
    });
  },

  goGoods(e) {
    // my.alert({ content: "goGoods" });
    my.tb.openDetail({
      itemId: e.goodId,
      success: (res) => {

      },
      fail: (res) => {
        my.alert({ content: "商品开小差了。" });
      },
    });
  },

  goJoin(e) {
    if (e == 0) {
      this.getMemberUrl();
    } else if (e == 1)
      this.jumpToUrl(benifitUrl);

    // my.showLoading({
    //   content: '加载中...',
    //   delay: 0,
    // });


    // this.goMember();
    // var temp = this.data.joinShowType;
    // this.setData({
    //   joinShowType:Math.abs(temp - 1)
    // })
  },
  ////////////////////////

  async getMember() {
    try {
      let info = await cloud.function.invoke('mmvr', {}, "getMember");
      let result = info.data.result;

      if (result.member_info) {
        this.setData({
          joinShowType: 1,
          showJoinParty: true
        })
        globalData.isMember = true;
        // this.jumpToBenifit(benifitUrl);
      } else {
        this.setData({
          joinShowType: 0,
          showJoinParty: true
        })
        globalData.isMember = false;
        // this.getMemberUrl();
      }

      console.log('goMember info----------', info);
    } catch (err) {
      console.log('goMember err-----------', err)
    } finally {
      my.hideLoading({
        page: this,
      });
    }
  },

  async getMemberUrl() {
    let member_url = await cloud.function.invoke('mmvr', { url: benifitUrl }, "getMemberUrl");
    this.jumpToUrl(member_url.data.result.result);
  },

  jumpToUrl(url) {
    my.call("navigateToOutside", {
      url: url
    }, (res) => {
      console.log("res3333", res);
    });
  },

  /**
  * 启动计时器
  */
  countDown() {
    let that = this;

    if (that.timer != null)
      return;

    my.showLoading({
      content: '加载中...',
      delay: 0,
    });
    let countDownNum = 4;//获取倒计时初始值
    //如果将定时器设置在外面，那么用户就看不到countDownNum的数值动态变化，所以要把定时器存进data里面
    this.timer = setInterval(function () {//这里把setInterval赋值给变量名为timer的变量
      //每隔一秒countDownNum就减一，实现同步
      countDownNum--;
      //在倒计时还未到0时，这中间可以做其他的事情，按项目需求来
      if (countDownNum <= 0) {
        clearInterval(that.timer);

        that.timer = null;
        my.hideLoading({
          page: that
        });
      }
    }, 1000)
  },

  //////////////////////////

  addDebugInfo(info) {
    var str = info + "\n" + this.data.debugStr;
    this.setData({
      debugStr: str
    })
  }
});
